import { useCallback, useImperativeHandle, useState } from 'react';

export interface ICommonModalRefObject {
  open: (data?: any) => void;
  close: () => void;
}

// 默认的值
export const defaultCommonModalRefObject = {
  open: () => {},
  close: () => {},
};

export function useEnhanceModalRef<T = any>(
  ref: React.MutableRefObject<ICommonModalRefObject>,
  assign = true,
) {
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState<T>();

  const close = useCallback(() => {
    setVisible(false);
    setData(undefined);
  }, []);

  const open = useCallback((data?: T) => {
    setVisible(true);
    setData(data);
  }, []);

  useImperativeHandle(
    ref,
    () => {
      const ability = {
        close,
        open,
      };
      if (ref.current && ref) {
        Object.assign(ref.current, ability);
        return ref.current;
      }
      return ability;
    },
    [assign, close, open, ref],
  );

  return {
    visible,
    setVisible,
    close,
    open,
    data,
  };
}
